<?php

include_once("models/model.php");

class Controller {
	public $model;
	public function __construct() {
		$this->model = new Model();
	}

	public function invoke() {
		if (!isset($_GET['task'])) {
			if (!isset($_POST['task']))
				$task = NULL;
			else
				$task = $_POST['task'];
		}else $task = $_GET['task'];

		if (!isset($_GET['book'])&&!isset($task)) {
			// không có book nào được yêu cầu, list tất cả các books
			global $books;
			$books = $this->model->getBookList();
			include 'views/booklist.phtml';
		} else {
			switch ($task) {
				case "edit":
					$book = $this->model->getBook($_GET['book']);
					if ($book != NULL) {
						include 'views/editbook.phtml';
					}
				break;
				case "save":
					$book = $this->model->saveBook($_SESSION['datastore']);
					if ($book != NULL) {
						//chuyển hướng đến index.php
						if (headers_sent()) {
							//echo("<script>window.alert('Đã cập nhật!')</script>");
							echo "<script>document.location.href='javascript:history.go(-2)';</script>\n";
						} else {
							header('HTTP/1.1 301 Moved Permanently');
							header('Location: index.php');
						}
					}
					echo "<script>document.location.href='javascript:history.go(-2)';</script>\n";
				break;
				case "delete":
					$book = $this->model->deleteBook($_POST['bkey']);
					if (headers_sent()) {
						echo "<script>document.location.href='javascript:history.go(-2)';</script>\n";
					} else {
						header('HTTP/1.1 301 Moved Permanently');
						header('Location: index.php');
					}
				break;
				default:
					// hiển thị book đã yêu cầu
					global $book;
					$book = $this->model->getBook($_GET['book']);
					if ($book != NULL)
						include 'views/viewbook.phtml';
					break;
			}
		}
	}
}